package com.sinry.api.aggregation.handler;

import com.github.xiaoymin.knife4j.aggre.core.pojo.BasicAuth;
import com.github.xiaoymin.knife4j.aggre.nacos.NacosRoute;
import com.github.xiaoymin.knife4j.aggre.spring.configuration.Knife4jAggregationProperties;
import com.github.xiaoymin.knife4j.aggre.spring.support.NacosSetting;
import com.sinry.api.aggregation.entity.ApiRegister;
import com.sinry.api.aggregation.service.ApiRegisterService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author linxinlei
 * @project sinry-cloud
 * @description 接口注册
 * @date 2022/5/22
 **/
@Slf4j
@Configuration
public class ApiRegisterHandler {

    @Resource
    ApiRegisterService apiRegisterService;

    @Bean
    @Primary
    @ConditionalOnProperty(name = "knife4j.nacos.enable",havingValue = "true")
    public Knife4jAggregationProperties rewriteRoutes(@Autowired Knife4jAggregationProperties aggProperties) {
        NacosSetting nacos = aggProperties.getNacos();
        List<NacosRoute> nacosRoutes = this.getRoutes();
        nacos.setRoutes(nacosRoutes);
        aggProperties.setNacos(nacos);
        return aggProperties;
    }

    private List<NacosRoute> getRoutes() {
        List<NacosRoute> routes = new ArrayList<>();
        // 从缓存读取，没有则读数据库，再没有则等待
        List<ApiRegister> list = apiRegisterService.list();
        String serviceNames = list.stream().map(ApiRegister::getServiceName).collect(Collectors.joining(","));
        log.info("读取到服务接口：{}", serviceNames);
        for (ApiRegister apiRegister : list) {
            NacosRoute nacosRoute = new NacosRoute();
            nacosRoute.setName(apiRegister.getName());
            nacosRoute.setServiceName(apiRegister.getServiceName());
            nacosRoute.setLocation(apiRegister.getLocation());
            nacosRoute.setServicePath(apiRegister.getServicePath());
            nacosRoute.setSwaggerVersion(apiRegister.getSwaggerVersion());
            nacosRoute.setGroupName(apiRegister.getGroupName());
            nacosRoute.setClusters(apiRegister.getClusters());
            nacosRoute.setOrder(apiRegister.getOrder());
            nacosRoute.setNamespaceId(apiRegister.getNamespaceId());
            BasicAuth basicAuth = new BasicAuth();
            basicAuth.setEnable(apiRegister.getBasicAuthEnable() == 1);
            basicAuth.setUsername(apiRegister.getBasicUsername());
            basicAuth.setPassword(apiRegister.getBasicPassword());
            nacosRoute.setRouteAuth(basicAuth);
            routes.add(nacosRoute);
        }
        return routes;
    }
}
